<!-- 圖片上傳 -->
<template>
  <div>
      <div class="uploadImage-box">
          <div class="showImage" :key="index" v-for="(item,index) in uploadImgArr">
               <div class="uploadImg"  :style="{backgroundImage:'url('+item.imgUrl+')',width:width+'px',height:height+'px'}"></div>
               <div class="uploadBg" v-if="!isDisabled">
                   <span class="iconfont icon-shanchu" @click="deleteImg(item.id)"></span>
               </div>
          </div>
          <div class="uploadBtn" v-if="uploadImgArr.length<9&&isDisabled==false" :style="{width:width+'px',height:height+'px'}">
              <common-icon type="_shangchuan" :size="26"></common-icon>
              <p class="introText">{{introText}}</p>
              <input id="uploaderInput" class="uploader-input"
              type="file" name="files" accept="image/*" @click="clearFile" @change="uploadImage($event)" />
          </div>
      </div>
      <Alert v-if="isShowAlert" type="error" style="width: 220px;margin-top: 10px;" show-icon>图片大小不能超过500K！</Alert>
  </div>
</template>

<script>
import commonIcon from "_c/common-icon/common-icon.vue"
import { upLoadImg } from "@/api/data";
import { getImgUrl } from "@/api/server-url";

export default {
    props:{
        imgUrl:{
            type:String,
            default:''
        },
        // 这个改为必传的参数
        uploadType:{
            type:String,
            default:'tmp'
        },
        imgIndex:{
            type:Number,
            default:0
        },
        width:{
            type:Number,
            default:180
        },
        height:{
            type:Number,
            default:120
        },
        introText:{
            type:String,
            default:''
        },
        showuploadImg: {
            type: Array,
            default: () => {
                return [];
            }
        },
        // 是否禁用，禁用的话不能添加或者删除，只能查看
        isDisabled: {
            type:Boolean,
            default:false
        }
    },
  data () {
    return {
        uploadImg: '',
        imgSize:1024*500,
        uploadImgArr:[],
        isShowAlert: false
    };
  },

  methods: {

      guid() {
            return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
                return v.toString(16);
            })
        },
      deleteImg(id){

          this.uploadImgArr = this.uploadImgArr.filter(item=>{
              return item.id!=id;
          })
          this.$emit('uploadImgData',this.uploadImgArr,this.imgIndex)
          console.log(this.uploadImgArr);

      },
      clearFile(e) {
          e.target.value = '';
      },
      uploadImage(event){
           let files = event.target.files[0] || event.dataTransfer.files[0];
           let filesSize = files.size;
           if(this.uploadImgArr.length>9){return;}
           if (filesSize > this.imgSize) {
               this.isShowAlert = true;
                setTimeout(()=> {
                    this.isShowAlert = false;
                }, 2000);
               return false;
           }
           let src, url = window.URL || window.webkitURL || window.mozURL;
           if (url) {
                src = url.createObjectURL(files);
            } else {
                src = event.target.result;
            }
            // this.uploadImg=src;
            // var arr = {
            //         id:this.uploadImgArr.length-1,
            //         imgName:src,
            //         imgUrl:src
            //     }
            //     this.uploadImgArr.push(arr)
                // this.uploadImgArr[0].img=src;

            let formData= new FormData();
            formData.append("files",files)

            upLoadImg(formData,this.uploadType).then(res => {
                if(res.data.code==200 || res.data.code==201){

                    var obj = {
                        id:this.guid(),
                        imgName:res.data.data.name,
                        imgUrl:getImgUrl(res.data.data.name)
                    }

                    this.uploadImgArr.push(obj)
                   return 1;
                }
            }).then(result=>{
                if(result == 1) this.$emit('uploadImgData',this.uploadImgArr,this.imgIndex);
            })
      },
  },

  computed: {
      returnUrl(){
         this.uploadImg = getImgUrl(this.imgUrl)
      }
  },

  mounted(){
    //   console.log(this.imgUrl)
    // console.log('文件存放位置' + this.uploadType);
    if(this.uploadType == '') {
        this.$Message.error('uploadMultiple组件未传入uploadType，请检查');
    }
    // console.log(8888888888)
  },
  watch:{
    // showuploadImg(now,old){
    //   console.log(now);
    //   console.log(8888888888)
    //   var that = this
    //   this.uploadImgArr= []
    //     now.forEach(item => {
    //   var obj = {
    //     id: that.guid(),
    //     imgName: item,
    //     imgUrl: getImgUrl(item)
    //   };
    //   this.uploadImgArr.push(obj);
    //   });
    // },
    showuploadImg: {
      handler(now, old) {
        //   console.log(now);
        //   console.log(8888888888)
          var that = this
          this.uploadImgArr= []
          now.forEach(item => {
            var obj = {
              id: that.guid(),
              imgName: item,
              imgUrl: getImgUrl(item)
            };
            this.uploadImgArr.push(obj);
          });
      },
      immediate: true,
      deep: false
    },
    returnUrl(a,b){
        console.log(a)
        console.log(b)
    }
  },
  components: {
      commonIcon
  },

}

</script>
 <style lang='less' >
   @import '../../less/variable.less';
    .uploadImage-box{
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
        &>div{
            border-radius: 5px;
            overflow: hidden;
            margin-right: 15px;
            margin-bottom: 15px;
        }
        .showImage{
            display: flex;
            position: relative;
            &:hover{
                .uploadBg{
                    display: flex;
                }
            }
            .uploadBg{
                position: absolute;
                top: 0;
                bottom: 0;
                left: 0;
                right: 0;
                background: rgba(0, 0, 0, 0.6);
                display: none;
                justify-content: center;
                align-items: center;
                .iconfont{
                    color: #ffffff;
                    font-size: 36px;
                    padding: 0 5px;
                    cursor: pointer;
                    &:hover{
                        color: @mainColor;
                    }
                }
            }
            .uploadImg{
                 background-position: center;
                 background-size: cover;
                 border: 1px dashed #e5e5e5;

                img{
                    width: 100%;
                }
            }
        }
        .uploadBtn{
            position: relative;
            cursor: pointer;
            display: flex;
            justify-content: center; /* 水平居中 */
            align-items: center;     /* 垂直居中 */
            border: 1px dashed #e5e5e5;
            &:hover{
                border-color:@mainColor;
                .iconfont{
                    color: @mainColor;
                }
            }
            &>.iconfont {
              color: #474747;
            }
            .uploader-input{
                position: absolute;
                z-index: 2;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                opacity: 0;
                cursor: pointer;
            }
        }

    }
</style>
